package club.smartdot.filter;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

// @Component
public class TokenFilter extends ZuulFilter {

	@Override
	public boolean shouldFilter() {
		// 表示过滤器是否生效即，是否启用
		return true;
	}

	@Override
	public Object run() throws ZuulException {
		// 业务逻辑···
		
		// 1. 获取上下文
		RequestContext currentContext = RequestContext.getCurrentContext();
		// 2. 获取Request
		HttpServletRequest request = currentContext.getRequest();
		// 3. 获取token的时候，从请求头获取,演示通过url传参
		// String userToken = request.getHeader("userToken");
		String userToken = request.getParameter("userToken");
		if(StringUtils.isEmpty(userToken)) {
			// 不继续执行
			currentContext.setSendZuulResponse(false);
			// 返回一个错误提示
			currentContext.setResponseBody("userToken is null");
			currentContext.setResponseStatusCode(401);
			return null;
		}
		return null;
	}

	@Override
	public String filterType() {
		// 表示过滤器类型: pre表示请求之前进行执行
		return "pre";
	}

	@Override
	public int filterOrder() {
		// 过滤器执行的顺序，即优先级
		return 0;
	}

}
